package com.producteev4j.marshall;

import com.producteev4j.exceptions.ProducteevUnmarshallException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by IntelliJ IDEA.
 * User: jcarrey
 * Date: 4/07/11
 * Time: 17:20
 * To change this template use File | Settings | File Templates.
 */
public class JacksonMappingUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();


    private static boolean canRead(final Class<?> clazz) {
        JavaType javaType = getJavaType(clazz);
        return objectMapper.canDeserialize(javaType);
    }

    private static JavaType getJavaType(final Class<?> clazz) {
        return TypeFactory.type(clazz);
    }

    public static Object read(final InputStream inputStream, final Class<?> clazz) throws ProducteevUnmarshallException {
        try {
            if (canRead(clazz)) {
                return objectMapper.readValue(inputStream, getJavaType(clazz));
            } else {
                throw new ProducteevUnmarshallException("Cannot read json on this class:" + clazz.getName());
            }
        } catch (JsonParseException ex) {
            throw new ProducteevUnmarshallException("Cannot read IS:" + ex, ex);
        } catch (JsonMappingException e) {
            throw new ProducteevUnmarshallException("Cannot read IS:" + e, e);
        } catch (IOException e) {
            throw new ProducteevUnmarshallException("Cannot read IS:" + e, e);
        }
    }
}
